package org.alis.rpc.common.paap.config;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.Set;

/**
 * @author lc
 * @version v1.0.0
 * @date 2020/8/28 11:29
 * @className P.class
 */
public class ParseStringValueSpring5 {

    protected static final String PLACEHOLDER_CLASS_SPRING5 = "org.springframework.util.PropertyPlaceholderHelper";

    private String placeholderPrefix = "${";

    private String placeholderSuffix = "}";

    private String valueSeparator = ":";

    private Object instance;

    private Method method;

    protected ParseStringValueSpring5(Class<?> clazz) {
        try {
            Constructor constructor = clazz.getDeclaredConstructor(String.class, String.class, String.class, boolean.class);
            instance = constructor.newInstance(placeholderPrefix, placeholderSuffix, valueSeparator, false);
            method = clazz.getDeclaredMethod("replacePlaceholders", String.class, Properties.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected String parseStringValue(String strVal, Properties props, Set<?> visitedPlaceholders) {
        try {
            return (String) method.invoke(instance, strVal, props);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setPlaceholderPrefix(String placeholderPrefix) {
        this.placeholderPrefix = placeholderPrefix;
    }

    public void setPlaceholderSuffix(String placeholderSuffix) {
        this.placeholderSuffix = placeholderSuffix;
    }

    public void setValueSeparator(String valueSeparator) {
        this.valueSeparator = valueSeparator;
    }
}
